package org.jeecg.modules.travel.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.constant.FillRuleConstant;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.modules.travel.dto.theme.ThemeAddDto;
import org.jeecg.modules.travel.dto.theme.ThemeEditDto;
import org.jeecg.modules.travel.entity.JhAttraction;
import org.jeecg.modules.travel.mapper.JhAttractionMapper;
import org.jeecg.modules.travel.mapper.JhThemeMapper;
import org.jeecg.modules.travel.entity.JhTheme;
import org.jeecg.modules.travel.service.IJhThemeService;
import org.jeecg.modules.travel.vo.theme.JhThemeTreeVo;
import org.jeecg.modules.travel.vo.theme.ThemeListVo;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 主题分类
 * @Author: jeecg-boot
 * @Date:   2025-04-19
 * @Version: V1.0
 */
@Slf4j
@Service
public class JhThemeServiceImpl extends ServiceImpl<JhThemeMapper, JhTheme> implements IJhThemeService {

    @Resource
    private JhAttractionMapper jhAttractionMapper;

    @Override
    public IPage<JhTheme> getMaxCodeDepart(Page<JhTheme> page, String parentId) {
        QueryWrapper<JhTheme> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(StringUtils.isNotBlank(parentId),JhTheme::getParentId, parentId)
                .isNull(StringUtils.isBlank(parentId),JhTheme::getParentId);
        return page(page,wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveTheme(ThemeAddDto dto) {
        if (StringUtils.isNotBlank(dto.getParentId())) {
            JhTheme parent = getById(dto.getParentId());
            if (parent == null) {
                return "父节点不存在";
            }
        }
        JSONObject formData = new JSONObject();
        formData.put("parentId",dto.getParentId());
        String[] codeArray = (String[]) FillRuleUtil.executeRule(FillRuleConstant.THEME_CODE,formData);
        JhTheme theme = new JhTheme();
        theme.setParentId(dto.getParentId())
                .setThemeCode(codeArray[0])
                .setThemeName(dto.getThemeName())
                .setThemeIcon(dto.getThemeIcon())
                .setThemeLevel(Integer.valueOf(codeArray[1]))
                .setThemePath(dto.getThemePath())
                .setSortOrder(dto.getSortOrder());
        boolean flag = this.save(theme);
        if (!flag) {
            return "添加失败";
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updateThemeById(ThemeEditDto dto) {
        JhTheme jhTheme = getById(dto.getId());
        if (jhTheme == null) {
            return "主题不存在";
        }
        UpdateWrapper<JhTheme> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(JhTheme::getId,dto.getId())
                .set(JhTheme::getParentId,dto.getParentId())
                .set(JhTheme::getThemeName,dto.getThemeName())
                .set(JhTheme::getThemeIcon,dto.getThemeIcon())
                .set(JhTheme::getThemePath,dto.getThemePath())
                .set(JhTheme::getSortOrder,dto.getSortOrder());
        boolean flag = this.update(updateWrapper);
        if (!flag) {
            return "编辑失败";
        }
        return null;
    }

    @Override
    public String removeThemeById(String id) {
        JhTheme theme = this.getById(id);
        if (theme == null) {
            return "主题不存在";
        }
        List<String> ids = baseMapper.themeIds(theme.getId());
        QueryWrapper<JhAttraction> wrapper = new QueryWrapper<>();
        wrapper.lambda().in(JhAttraction::getAttractionTheme,ids);
        long size = jhAttractionMapper.selectCount(wrapper);
        if (size > 0) {
            return "该主题下有景点，无法删除";
        }
        // 根据themePath删除所有子节点（如path like '/A010%'）
        int flag = baseMapper.deleteBatchIds(ids);
        if (flag == 0) {
            return "删除失败";
        }
        return null;
    }

    @Override
    public List<JhThemeTreeVo> getThemeTree() {
        List<JhTheme> allThemes = this.list(new LambdaQueryWrapper<JhTheme>()
                .orderByAsc(JhTheme::getSortOrder));
        return buildTreeRecursive(allThemes); // 从根节点开始递归
    }

    @Override
    public List<ThemeListVo> appThemeList() {
        QueryWrapper<JhTheme> wrapper = new QueryWrapper<>();
        wrapper.lambda().isNull(JhTheme::getParentId).or().eq(JhTheme::getParentId, 0)
                .orderByAsc(JhTheme::getSortOrder);
        List<JhTheme> list = list(wrapper);
        return list.stream().map(ThemeListVo::new).collect(Collectors.toList());
    }


    /**
     * 将平面列表转换为树形结构（递归实现）
     * @param flatList 平面结构的数据列表
     * @return 树形结构数据
     */
    public List<JhThemeTreeVo> buildTreeRecursive(List<JhTheme> flatList) {
        // 1. 参数校验
        if (flatList == null || flatList.isEmpty()) {
            return Collections.emptyList();
        }
        // 2. 准备返回的树形结构
        List<JhThemeTreeVo> tree = new ArrayList<>();
        // 3. 找出所有根节点（parentId为null的节点）
        List<JhTheme> rootEntities = flatList.stream()
                .filter(entity -> StringUtils.isBlank(entity.getParentId()))
                .toList();
        // 4. 递归构建树
        for (JhTheme root : rootEntities) {
            JhThemeTreeVo parent = new JhThemeTreeVo(root);
            buildChildren(parent, flatList);
            tree.add(parent);
        }
        // 5. 按sortOrder排序
        sortTreeByOrder(tree);
        return tree;
    }

    /**
     * 递归构建子节点
     * @param parentNode 当前父节点
     * @param allEntities 所有实体列表
     */
    private void buildChildren(JhThemeTreeVo parentNode, List<JhTheme> allEntities) {
        // 1. 找出当前节点的所有直接子节点
        List<JhTheme> childrenEntities = allEntities.stream()
                .filter(entity -> parentNode.getId().equals(entity.getParentId()))
                .collect(Collectors.toList());
        // 2. 如果没有子节点，直接返回
        if (childrenEntities.isEmpty()) {
            return;
        }
        // 3. 初始化children集合（如果尚未初始化）
        if (parentNode.getChildren() == null) {
            parentNode.setChildren(new ArrayList<>());
        }
        // 4. 为每个子节点递归构建
        for (JhTheme childEntity : childrenEntities) {
            JhThemeTreeVo childNode = new JhThemeTreeVo(childEntity);
            parentNode.getChildren().add(childNode);
            buildChildren(childNode, allEntities);
        }
        // 5. 对子节点按sortOrder排序
        sortChildrenByOrder(parentNode.getChildren());
    }

    /**
     * 对树进行排序
     */
    private void sortTreeByOrder(List<JhThemeTreeVo> tree) {
        if (tree == null || tree.isEmpty()) return;
        // 按sortOrder排序（需处理可能的null值）
        tree.sort(Comparator.comparing(
                node -> StringUtils.isNotBlank(node.getSortOrder()) ? node.getSortOrder() : "",
                Comparator.nullsLast(Comparator.naturalOrder())
        ));
        // 递归排序子节点
        tree.forEach(node -> {
            if (node.getChildren() != null) {
                sortTreeByOrder(node.getChildren());
            }
        });
    }

    /**
     * 对子节点列表排序
     */
    private void sortChildrenByOrder(List<JhThemeTreeVo> children) {
        if (children == null || children.isEmpty()) return;
        children.sort(Comparator.comparing(
                node -> StringUtils.isNotBlank(node.getSortOrder()) ? node.getSortOrder() : "",
                Comparator.nullsLast(Comparator.naturalOrder())
        ));
    }

}
